<template>
    <div class="TeacherManager">
        <div class="tableBar">

            <!-- 导航 -->
            <div class="nav">
                <el-input v-model="input" placeholder="请输入教师姓名" style="width: 250px;margin-top: 15px;" clearable
                    @keyup.enter.native="handleQuery">
                    <i slot="prefix" class="el-input__icon el-icon-search" style="cursor: pointer" @click="handleQuery"></i>
                </el-input>
                <el-button style="height: 50px; margin-top: 10px; margin-right: 20px;" type="primary"
                    @click="addMemberHandle()">
                    + 添加教师
                </el-button>
            </div>


            <!-- 数据表 -->
            <el-table style="margin-top: 30px; width: 99%;" :data="tableData" stripe class="tableBox" :height="400">
                <el-table-column type="index" width="50">
                </el-table-column>
                <el-table-column prop="jiaoshixingming" label="教师姓名"></el-table-column>
                <el-table-column prop="name" label="教师账号"></el-table-column>
                <el-table-column prop="photo" label="教师头像">
                    <template slot-scope="scope">
                        <el-image style="height: 40px; border:none;cursor: pointer; border-radius: 5px;"
                            :src="getImage(scope.row.photo)"
                            :preview-src-list="[`http://localhost:8086/common/download?name=${scope.row.photo}`]">
                        </el-image>
                    </template>
                </el-table-column>
                <el-table-column prop="sex" label="性别" width="90"></el-table-column>
                <el-table-column prop="zhicheng" label="职称"></el-table-column>
                <el-table-column prop="tel" label="手机号"></el-table-column>
                <el-table-column prop="email" label="教师邮箱"></el-table-column>

                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button type="text" size="medium" class="blueBug" @click="update(scope.row)">
                            修改
                        </el-button>
                        <el-button type="text" size="medium" class="delBut non" @click="deleteHandle(scope.row.id)">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页栏 -->
            <el-pagination class="pageList" :page-sizes="[3, 6, 9, 12]" :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper" :total="counts" :current-page.sync="page"
                @size-change="handleSizeChange" @current-change="handleCurrentChange">
            </el-pagination>





            <!-- 添加学生 -->
            <el-dialog :title=mytitle :visible.sync="dialogVisible" width="30%" @close="resetForm('teacherForm')">
                <el-form :model="teacherForm" status-icon :rules="teacherRules" ref="teacherForm" label-width="100px"
                    class="demo-ruleForm">

                    <el-form-item label="用户名" prop="name">
                        <el-input v-model="teacherForm.name" prefix-icon="el-icon-user" placeholder="请输入用户名"></el-input>
                    </el-form-item>
                    <el-form-item label="密码" prop="pass">
                        <el-input type="password" v-model="teacherForm.pass" prefix-icon="el-icon-lock" placeholder="请输入密码"
                            show-password autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="确认密码" prop="checkPass">
                        <el-input type="password" v-model="teacherForm.checkPass" prefix-icon="el-icon-lock"
                            placeholder="请确认密码" show-password autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="教师姓名" prop="jiaoshixingming" v-if="mytitle === '修改教师'">
                        <el-input v-model="teacherForm.jiaoshixingming" placeholder="请输入手机号"></el-input>
                    </el-form-item>
                    <el-form-item label="教师性别" prop="sex" v-if="mytitle === '修改教师'">
                        <el-input v-model="teacherForm.sex" placeholder="请输入性别"></el-input>
                    </el-form-item>
                    <el-form-item label="教师邮箱" prop="email" v-if="mytitle === '修改教师'">
                        <el-input v-model="teacherForm.email" placeholder="请输入性别"></el-input>
                    </el-form-item>
                    <el-form-item label="联系方式" prop="tel">
                        <el-input v-model.number="teacherForm.tel" prefix-icon="el-icon-postcard"
                            placeholder="请输入手机号"></el-input>
                    </el-form-item>
                    <el-form-item label="职称" prop="zhicheng">
                        <el-input v-model="teacherForm.zhicheng" placeholder="请输入职称"></el-input>
                    </el-form-item>

                </el-form>


                <div slot="footer" class="dialog-footer">
                    <span slot="footer" class="dialog-footer">
                        <el-button @click="resetForm('teacherForm')">取 消</el-button>
                        <el-button type="primary"
                            @click="submitForm('teacherForm', mytitle === '教师注册' ? 'add' : 'update')">确
                            定</el-button>
                    </span>
                </div>

            </el-dialog>



        </div>
    </div>
</template>

<script>
export default {
    name: 'TeacherManager',
    data() {

        //判断学生手机号是否合理
        var checkStn = (rule, value, callback) => {
            if (!value) {
                return callback(new Error('手机号不能为空'));
            }
            setTimeout(() => {
                if (!Number.isInteger(value)) {
                    callback(new Error('请输入数字值'));
                } else {
                    callback();
                }
            }, 1000);
        };

        //密码为空时弹出提示信息teacherForm
        var teacherFormValidatePass = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入密码'));
            } else {
                if (this.teacherForm.checkPass !== '') {
                    this.$refs.teacherForm.validateField('checkPass');
                }
                callback();
            }
        };

        //验证两次密码不一致teacherForm
        var teacherFormValidatePass2 = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请再次输入密码'));
            } else if (value !== this.teacherForm.pass) {
                callback(new Error('两次输入密码不一致!'));
            } else {
                callback();
            }
        };

        return {
            dialogVisible: false,
            mytitle: "",
            //输入框内容
            input: '',
            //总数据条数
            counts: 0,
            //当前页
            page: 1,
            //每页条数
            pageSize: 3,
            // 表格数据
            tableData: [],
            //学生注册信息
            teacherForm: {
                name: "",
                pass: "",
                checkPass: "",
                tel: "",
                id: "",
                zhicheng: "",
                jiaoshixingming: "",
                sex: "",
                email: "",
            },
            //学生表单验证的的规则
            teacherRules: {
                name: [
                    { message: '请输入用户名称', trigger: 'blur' },
                    { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                ],
                pass: [
                    { validator: teacherFormValidatePass, trigger: 'blur' }
                ],
                checkPass: [
                    { validator: teacherFormValidatePass2, trigger: 'blur' }
                ],
                tel: [
                    { validator: checkStn, trigger: 'blur' }
                ],
                zhicheng: [
                    { message: '请输入职称', trigger: 'blur' },
                    { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
                ]
            },
        }
    },
    methods: {
        //输入框查询
        handleQuery() {
            this.getTableData();
        },
        // 打开注册框
        addMemberHandle() {
            this.dialogVisible = true;
            this.mytitle = "教师注册";
            Object.keys(this.teacherForm).forEach((key) => (this.teacherForm[key] = ''))
        },

        //添加学生
        submitForm(formName, methodName) {
            console.log(this.teacherForm);
            this.$refs[formName].validate((valid) => {
                let messageNow = ""
                //初次访问为update时，取消验证
                if (methodName === "update") {
                    valid = true;
                }
                if (valid) {
                    if (methodName === "add") {
                        //添加用户时，id为空
                        // 信息无误，准备写入后端，判断是那个注册信息发送对应的请求
                        this.axios.post("/teacher/save", this.teacherForm)
                            .then(res => {
                                if (res.data === "success") {
                                    messageNow = "恭喜你，教师注册成功！";
                                    this.$notify({
                                        showClose: true,
                                        message: messageNow,
                                        type: 'success',
                                        duration: 1000
                                    });
                                }
                            })
                        this.getTableData();
                        this.dialogVisible = false;
                    }
                    else if (methodName === "update") {
                        this.axios.post("/teacher/update", this.teacherForm)
                            .then(res => {
                                if (res.data === "success") {
                                    this.$message({
                                        message: '恭喜你，修改成功',
                                        type: 'success'
                                    });
                                }
                                this.getTableData();
                            })
                        this.dialogVisible = false;
                    }
                }
                else {
                    this.$notify({
                        showClose: true,
                        message: "注册失败，请重新注册！",
                        type: 'error',
                        duration: 1000
                    });
                    //注册失败重置表单验证
                    this.dialogVisible = false;
                }
            });
        },


        //取消添加学生重置内容
        resetForm(formName) {
            this.$refs[formName].resetFields();
            this.dialogVisible = false;

        },

        handleSizeChange(val) {
            this.pageSize = val;
            this.page = 1;
            this.getTableData();
        },
        handleCurrentChange(val) {
            this.page = val;
            this.getTableData();
        },
        getImage(image) {
            return `http://localhost:8086/common/download?name=${image}`
        },
        getTableData() {
            const params = {
                params: {
                    page: this.page,
                    pageSize: this.pageSize,
                    name: this.input,
                }
            }
            this.axios.get("/teacher/page", params)
                .then(res => {
                    this.counts = res.data.total;
                    this.tableData = res.data.records;
                    console.log("教师");
                    console.log(this.tableData);
                })
        },
        update(val) {
            this.dialogVisible = true;
            this.mytitle = "修改教师";
            this.teacherForm.pass = val.pass;
            this.teacherForm.checkPass = val.pass;
            this.teacherForm.name = val.name;
            this.teacherForm.tel = val.tel;
            this.teacherForm.id = val.id;
            this.teacherForm.zhicheng = val.zhicheng;
            this.teacherForm.jiaoshixingming = val.jiaoshixingming;
            this.teacherForm.sex = val.sex

        },
        deleteHandle(val) {
            this.$confirm('此操作将永久删除该教师, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.axios.delete("/teacher/delete/" + val)
                    .then(res => {
                        if (res.data === "success") {
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                            this.getTableData();
                        }
                    })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        }
    },
    mounted() {
        this.getTableData();
    },
}

</script>
<style scoped>
.tableBar .el-input__icon el-icon-search {
    height: 14px;
}

.nav {
    width: 100%;
    display: flex;
    justify-content: space-between;

}

.tableBar {
    padding-left: 10px;
    background-color: #ffffff;
    height: 600px;
    width: 99.2%;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    padding-left: 10px;
    margin-top: 10px;
}

.tableBox {
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.2);
}

.pageList {
    margin-top: 25px;
    text-align: center;
}
</style>